package cn.pzhu.services.web;

import cn.pzhu.model.Achievement;
import cn.pzhu.model.Logistics;
import cn.pzhu.model.Order;
import cn.pzhu.model.User;
import cn.pzhu.services.BaseServices;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by dongp on 2016/5/8.
 */
public class WebOrderServices extends BaseServices{

    private WebAcheievementServices acheievementServices = new WebAcheievementServices();
    private WebLogistics webLogistics = new WebLogistics();

    public boolean addOrder(int id,int quantity,String logisticID,String address, String postCode, String recipient,
                            String phone, String transport, User user) {

        Achievement achievement = acheievementServices.queryDetail(id);
        String name = achievement.getStr("name");
        String imgurl = achievement.getStr("imgeurl");
        double uPrice = achievement.getDouble("money");
        double rebate = achievement.getDouble("rebate");
        double total = uPrice*quantity - rebate;
        int userID = user.getInt("userID");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        boolean rst = false;
        // 判断是否用新地址
        if(logisticID == null && !"".equals(logisticID) && address == null && !"".equals(address)) {
            return false;
        }
        if(logisticID != null && !"".equals(logisticID) && (address == null || "".equals(address))) {
            rst = new Order().set("userID",userID).set("logisticsID", logisticID).set("name",name).set("imgurl",imgurl).
                set("uPrice", uPrice).set("rebate", rebate).set("quantity",quantity).set("total",total).set("status",0)
                .set("tradeDate", format.format(new Date()))
                .save();
        }else {
            int lgcId = webLogistics.addLogistic(userID, recipient, phone, address, transport, postCode);
            rst = new Order().set("userID", userID).set("logisticsID", lgcId).set("name", name).set("imgurl", imgurl).
                    set("uPrice", uPrice).set("rebate", rebate).set("quantity", quantity).set("total", total)
                    .set("tradeDate",format.format(new Date()))
                    .set("status", 0).save();
        }
        return rst;
    }

    public List<Order> queryOrder(int userID){
        List<Order> orders = Order.dao.find("select t1.*,t2.dName from goods t1 left join dict t2 on t1.status = t2.dVal where userID = ?",userID);
        return orders;
    }
}
